package cn.zb.dao;

import java.util.List;













import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import cn.zb.pojo.*;
@Repository
public class TopicDao {
	@Resource
	private HibernateTemplate template;
	//获取某区域帖子
	public List<Topic> select(int id)
	{
		return (List<Topic>) template.find("from Topic where SId=?", id);
	}
	//分页获取某区域帖子
	public List<Topic> select(final int id,final int page,final int limit)
	{
		return  template.execute(new HibernateCallback<List<Topic>>() {
			@Override
			public List<Topic> doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
			Query<Topic> query=session.createQuery("from Topic where SId="+id,Topic.class);	
			             query.setFirstResult((page-1)*limit);
			             query.setMaxResults(limit);
				return  query.list();
			}
		});
	}
	//分页查询所有帖子
	public List<Topic> select(final int page,final int limit)
		{
		return  template.execute(new HibernateCallback<List<Topic>>() {

			@Override
			public List<Topic> doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
			Query<Topic> query=session.createQuery("from Topic",Topic.class);	
			             query.setFirstResult((page-1)*limit);
			             query.setMaxResults(limit);
				return  query.list();
			}
		});
		}
	//获取所有帖子
	public List<Topic> select()
	{
		return (List<Topic>) template.find("from Topic order by publish asc",null );
	}
	public boolean insert(Topic topic)
	{		
		template.saveOrUpdate(topic);
		return true;
	}
	//获取特定帖子
	public Topic theSelect(int id)
	{
		return  template.get(Topic.class, id);
	}
	public Boolean delect(int id){		
		template.delete(this.theSelect(id));
		return true;
	}
	//修改帖子
	public Boolean update(Topic topic){
	 Topic t=	this.theSelect(topic.getId());
	 t.setTitle(topic.getTitle());
	 t.setContent(topic.getContent());
		template.update(t);
		return true;
	}
	//查询相关标题的帖子
	public List<Topic> select(String title){
		return (List<Topic>) template.find("from Topic where title like ?","%"+title+"%");
	}
	//分页查询所有帖子
	public List<Topic> select(final String title,final int page,final int limit)
		{
		return  template.execute(new HibernateCallback<List<Topic>>() {

			@Override
			public List<Topic> doInHibernate(Session session) throws HibernateException {
					// TODO Auto-generated method stub
			Query<Topic> query=session.createQuery("from Topic where title LIKE '%"+title+"%'",Topic.class);	
				          query.setFirstResult((page-1)*limit);
				          query.setMaxResults(limit);
				return  query.list();
			}
		});
		}
}
